param(
    [Parameter(Position=0)]
    [ValidatePattern('^(stable|latest|\d+\.\d+\.\d+(-[^\s]+)?)$')]
    [string]$Target = "stable"
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$ProgressPreference = 'SilentlyContinue'

# Check for 32-bit Windows
if (-not [Environment]::Is64BitProcess) {
    Write-Error "Claude Code does not support 32-bit Windows. Please use a 64-bit version of Windows."
    exit 1
}

$COS_BUCKET = "https://claudecode-1301368149.cos.ap-guangzhou.myqcloud.com/claude-mirror"
$DOWNLOAD_DIR = "$env:USERPROFILE\.claude\downloads"

# Always use x64 for Windows (ARM64 Windows can run x64 through emulation)
$platform = "win32-x64"
New-Item -ItemType Directory -Force -Path $DOWNLOAD_DIR | Out-Null

# Always download stable version (which has the most up-to-date installer)
try {
    $versionResponse = Invoke-RestMethod -Uri "$COS_BUCKET/stable" -ErrorAction Stop
    $version = $versionResponse.Trim()
    Write-Output "Getting version: $version"
}
catch {
    Write-Error "Failed to get stable version: $_"
    exit 1
}

try {
    $manifestUrl = "$COS_BUCKET/$version/manifest.json"
    Write-Output "Fetching manifest from: $manifestUrl"
    $manifest = Invoke-RestMethod -Uri $manifestUrl -ErrorAction Stop
    $checksum = $manifest.platforms.$platform.checksum

    if (-not $checksum) {
        Write-Error "Platform $platform not found in manifest"
        exit 1
    }
}
catch {
    Write-Error "Failed to get manifest: $_"
    exit 1
}

# Download and verify
$binaryPath = "$DOWNLOAD_DIR\claude-$version-$platform.exe"
try {
    $downloadUrl = "$COS_BUCKET/$version/$platform/claude.exe"
    Write-Output "Downloading from: $downloadUrl"
    Invoke-WebRequest -Uri $downloadUrl -OutFile $binaryPath -ErrorAction Stop
}
catch {
    Write-Error "Failed to download binary: $_"
    if (Test-Path $binaryPath) {
        Remove-Item -Force $binaryPath
    }
    exit 1
}

# Calculate checksum
$actualChecksum = (Get-FileHash -Path $binaryPath -Algorithm SHA256).Hash.ToLower()

if ($actualChecksum -ne $checksum) {
    Write-Error "Checksum verification failed"
    Remove-Item -Force $binaryPath
    exit 1
}

# Check if .local\bin is in PATH before installation
$localBinPath = "$env:USERPROFILE\.local\bin"
$currentPath = [Environment]::GetEnvironmentVariable("PATH", "User")
$pathNeedsConfiguration = $currentPath -notlike "*$localBinPath*"

# Run claude install to set up launcher and shell integration
Write-Output "Setting up Claude Code..."
try {
    if ($Target) {
        & $binaryPath install $Target
    }
    else {
        & $binaryPath install
    }

    # Wait a moment for installation to complete
    Start-Sleep -Seconds 2

    # If PATH was not configured before installation, configure it now
    if ($pathNeedsConfiguration) {
        Write-Output ""
        Write-Output "Configuring PATH for Claude Code..."

        try {
            # Add to user PATH
            $newPath = $currentPath + ";" + $localBinPath
            [Environment]::SetEnvironmentVariable("PATH", $newPath, "User")

            # Also update current session
            $env:PATH = $env:PATH + ";" + $localBinPath

            Write-Output "[OK] PATH configured successfully"
            $pathConfigured = $true
            Write-Output ""
            Write-Output "[INFO] Note: Restart your terminal for PATH changes to take full effect."
            Write-Output "   Or run 'claude --version' to test immediately."
        }
        catch {
            Write-Warning "[WARNING] Failed to automatically configure PATH: $_"
            Write-Output ""
            Write-Output "Manual setup required:"
            Write-Output "Add '$localBinPath' to your PATH environment variable:"
            Write-Output "System Properties → Environment Variables → Edit User PATH → New"
            $pathConfigured = $false
        }
    }
    else {
        Write-Output ""
        Write-Output "[OK] PATH is already configured for Claude Code"
        $pathConfigured = $true
    }
}
finally {
    try {
        # Clean up downloaded file
        # Wait a moment for any file handles to be released
        Start-Sleep -Seconds 1
        Remove-Item -Force $binaryPath
    }
    catch {
        Write-Warning "Could not remove temporary file: $binaryPath"
    }
}

# Initialize pathConfigured variable for final message
if ($pathNeedsConfiguration) {
    $pathConfigured = $true  # Will be set to false if configuration fails
} else {
    $pathConfigured = $true  # Already configured
}

Write-Output ""
Write-Output "[SUCCESS] Installation complete!"

if (-not $pathNeedsConfiguration) {
    Write-Output ""
    Write-Output "[OK] Your PATH is already configured. You can use 'claude' immediately."
    Write-Output "  Run 'claude --version' to verify."
} else {
    Write-Output ""
    Write-Output "[OK] PATH has been automatically configured for you."
    Write-Output "  You can now use 'claude' from your terminal."
    Write-Output "  Run 'claude --version' to verify the installation."
}

Write-Output ""
